let path = require('path');
let router = require('koa-router')();
let Sequelize = require('sequelize');
const model = require('../../models/user_file');
let dao = require('../../dao/' + path.basename(__dirname));

let daoUserFile = require('../../dao/user_file');
let trimPost = require('../../utils/Interceptor/trimPost');
let md5 = require('../../utils/lib/md5');

const Koa = require("koa");
const app = new Koa();

router.put('v1/user/file', async function (ctx, next) {
    let {user_id, directory, new_path,} = ctx.request.body;
    try {
        await model.update({dictionary: new_path}, {
            where: {
                user_id: user_id,
                dictionary: directory,
            }
        });
        ctx.response.body = {};
    } catch (err) {
        ctx.response.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: "文件路径更改错误！"
        }
    }
})
router.post('v1/user/file', async function (ctx, next) {
    let {user_id, directory, new_name} = ctx.request.body;
    try {
        await model.create({
            directory: directory,
            user_id: user_id,
            filename: new_name
        });
        ctx.response.body = {};
    } catch (err) {
        ctx.response.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: "文件已存在！"
        }
    }
})
router.del('v1/user/file', async function (ctx, next) {
    let {user_id, directory} = ctx.request.body;
    try {
        await model.destroy({
            where: {
                directory: directory,
                user_id: user_id,
            }
        })
        // TODO 删除文件夹时删除该文件夹下的所有文件
        ctx.response.body = {};
    } catch (err) {
        ctx.response.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: "删除文件错误！"
        }
    }
})
router.get('v1/user/file', async function (ctx, next) {
    let {user_id, directory} = ctx.request.body;
    let fileList = await model.findAll({
        where: {
            user_id: user_id,
            directory: directory,
        }
    })
    if (fileList) {
        ctx.response.status = 200;
        ctx.type = 'json/application';
        ctx.response.body = {
            'statusCode': 200,
            'FileInfo': fileList,
        };
    } else {
        ctx.response.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: "该路径下没有文件和文件夹！"
        }
    }
})
module.exports = router.routes();